package com.wechat.gateway.controller;

import com.wechat.gateway.util.CryptoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 加密相关控制器
 */
@Slf4j
@RestController
@RequestMapping("/crypto")
public class CryptoController {

    @Autowired
    private CryptoUtil cryptoUtil;

    /**
     * 获取RSA公钥
     * 客户端使用此公钥加密敏感数据
     */
    @GetMapping("/public-key")
    public ResponseEntity<Map<String, Object>> getPublicKey() {
        log.info("客户端请求获取RSA公钥");
        Map<String, Object> result = new HashMap<>();
        try {
            String publicKey = cryptoUtil.getPublicKey();
            String cryptoMode = cryptoUtil.getCryptoMode();
            if (publicKey != null) {
                result.put("code", 200);
                result.put("message", "获取公钥成功");
                result.put("data", Map.of(
                        "publicKey", publicKey,
                        "cryptoMode", cryptoMode,
                        "algorithm", "RSA",
                        "keySize", "2048",
                        "usage", "客户端使用此公钥加密请求数据"
                ));
                result.put("timestamp", LocalDateTime.now());

                log.info("成功返回RSA公钥给客户端");
                return ResponseEntity.ok(result);
            } else {
                result.put("code", 500);
                result.put("message", "RSA公钥获取失败，可能未启用RSA模式");
                result.put("data", Map.of(
                        "cryptoMode", cryptoMode,
                        "suggestion", "请检查配置文件中的crypto.mode设置"
                ));
                result.put("timestamp", LocalDateTime.now());

                log.error("RSA公钥获取失败，当前加密模式: {}", cryptoMode);
                return ResponseEntity.internalServerError().body(result);
            }

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取公钥时发生异常: " + e.getMessage());
            result.put("timestamp", LocalDateTime.now());

            log.error("获取RSA公钥异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 测试加密解密功能
     */
    @PostMapping("/test")
    public ResponseEntity<Map<String, Object>> testCrypto(@RequestBody Map<String, String> request) {
        log.info("收到加密解密测试请求");
        Map<String, Object> result = new HashMap<>();
        try {
            String plainText = request.get("plainText");
            if (plainText == null || plainText.isEmpty()) {
                result.put("code", 400);
                result.put("message", "请提供要测试的明文数据");
                result.put("timestamp", LocalDateTime.now());
                return ResponseEntity.badRequest().body(result);
            }
            // 加密测试
            String encrypted = cryptoUtil.encrypt(plainText);
            // 解密测试
            String decrypted = cryptoUtil.decrypt(encrypted);
            boolean isSuccess = plainText.equals(decrypted);
            result.put("code", isSuccess ? 200 : 500);
            result.put("message", isSuccess ? "加密解密测试成功" : "加密解密测试失败");
            result.put("data", Map.of(
                    "originalText", plainText,
                    "encryptedText", encrypted,
                    "decryptedText", decrypted,
                    "testResult", isSuccess,
                    "cryptoMode", cryptoUtil.getCryptoMode()
            ));
            result.put("timestamp", LocalDateTime.now());

            log.info("加密解密测试完成，结果: {}", isSuccess ? "成功" : "失败");
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "加密解密测试异常: " + e.getMessage());
            result.put("timestamp", LocalDateTime.now());

            log.error("加密解密测试异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取加密配置信息
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getCryptoConfig() {
        log.info("客户端请求获取加密配置信息");

        Map<String, Object> result = new HashMap<>();

        try {
            result.put("code", 200);
            result.put("message", "获取加密配置成功");
            result.put("data", Map.of(
                    "cryptoMode", cryptoUtil.getCryptoMode(),
                    "supportedModes", new String[]{"RSA", "AES"},
                    "description", Map.of(
                            "RSA", "非对称加密，安全性高，适合密钥交换和小数据加密",
                            "AES", "对称加密，性能好，适合大数据加密"
                    ),
                    "usage", Map.of(
                            "encryption", "客户端使用公钥加密请求数据",
                            "decryption", "服务端使用私钥解密请求数据，使用公钥加密响应数据"
                    )
            ));
            result.put("timestamp", LocalDateTime.now());

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取加密配置异常: " + e.getMessage());
            result.put("timestamp", LocalDateTime.now());

            log.error("获取加密配置异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body(result);
        }
    }
} 